﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;

using BlueCMS.Core.Data;
using BlueCMS.Core.Data.Query;
using BlueCMS.Core.Entities;

namespace BlueCMS.Core.Services
{
    public class UserService : ServiceBase
    {
        public static User GetUserForWebsiteByName(Website website, string name)
        {
            SelectQuery query = new SelectQuery();
            query.Select.All();
            query.From.Table("cms_user_tbl");
            query.Where
                .Column("website_id").Equals().Parameter(website.website_id)
                .And()
                .Column("user_nm").Equals().Parameter(name);
            return query.ExecuteObject<User>();
        }

        public static User GetGuestUserForWebsite(Website website)
        {
            SelectQuery query = new SelectQuery();
            query.Select.All();
            query.From.Table("cms_user_tbl");
            query.Where
                .Column("website_id").Equals().Parameter(website.website_id)
                .And()
                .Column("isguest").Equals().Constant(true);
            return query.ExecuteObject<User>();
        }

        public static bool UserHasPermissionForNode(User user, string object_code, string permission_code, Node node)
        {
            SelectQuery query = new SelectQuery();
            query.Select.Aggregate("count(*)");
            query.From.Table("cms_node_permission_role_lnk").As("npr")
                .Join("cms_permission_tbl").As("p").On(c => c.Column("npr.permission_id").Equals().Column("p.permission_id"))
                .Join("cms_user_role_lnk").As("ur").On(c => c.Column("npr.role_id").Equals().Column("ur.role_id"))
                .Join("cms_nodeinheritsfrom_vw").As("nif").On(c => c.Column("npr.node_id").Equals().Column("nif.inheritsfrom_id"));
            query.Where
                .Column("nif.node_id").Equals().Parameter(node.node_id)
                .And()
                .Column("ur.user_id").Equals().Parameter(user.user_id)
                .And()
                .Column("p.object_cd").Equals().Parameter(object_code)
                .And()
                .Column("p.permission_cd").Equals().Parameter(permission_code);

            return query.ExecuteScalar<int>() > 0;
        }
    }
}
